package com.itheima.controller;

import org.springframework.data.domain.Page;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.BlogInfo;
import com.itheima.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/search")
@RestController
@CrossOrigin(allowCredentials="true", allowedHeaders="*", methods={RequestMethod.GET,RequestMethod.POST}, origins="*")
public class SearchController {

    @Autowired
    private SearchService searchService;
    /**
     * 初始化索引
     * @return
     */
    @PostMapping("/initElasticSearchIndex")
    public Result initElasticSearchIndex(){
        searchService.initElasticSearchIndex();
        return new Result("success","初始化索引成功");
    }

    /**
     * 根据uid添加索引
     * @param uid
     * @return
     */
    @PostMapping("/addElasticSearchIndexByUid")
    public Result addElasticSearchIndexByUid(@RequestParam("uid") String uid){
        searchService.addElasticSearchIndexByUid(uid);
        return new Result("success","添加成功");
    }

    /**
     * 根据uid删除索引
     * @param uid
     * @return
     */
    @PostMapping("/deleteElasticSearchByUid")
    public Result deleteElasticSearchByUid(@RequestParam("uid")String uid){
        searchService.deleteElasticSearchByUid(uid);
        return new Result("success","删除成功");
    }

    /**
     * 批量删除
     * @param uids
     * @return
     */
    @PostMapping("/deleteElasticSearchByUids")
    public Result deleteElasticSearchByUids(@RequestParam("uid")String[] uids){
        for (String uid : uids) {
            searchService.deleteElasticSearchByUid(uid);
        }
        return new Result("success","批量删除成功");
    }

     @PostMapping("/elasticSearchBlog")
    public Result elasticSearchBlog(@RequestParam("keywords")String keywords,@RequestParam("currentPage")Integer currentPage,@RequestParam("pageSize")Integer pageSize){
         Page<BlogInfo>blogPage=searchService.findPage(keywords,currentPage,pageSize);
         PageResult pageResult=new PageResult(blogPage.getTotalElements(),blogPage.getContent());
         return new Result("success",pageResult);
     }
}
